﻿using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;

namespace RuoVea.ExUtil.Validate;

/// <summary>
/// 描 述：用户登录账户
/// </summary>
public sealed class AccountNameAttribute : ValidationAttribute
{
    int _minLength = 8;
    int _maxLength = 32;

    /// <summary>
    /// 用户登录账户验证规则
    /// </summary>
    /// <param name="minLength">密码最小长度</param>  
    /// <param name="maxLength">密码最大长度</param>  
    /// <param name="msg">提示消息</param>
    public AccountNameAttribute(int minLength = 8, int maxLength = 32, string msg = null)
    {
        _minLength = minLength;
        _minLength = _minLength - 1;

        _maxLength = maxLength;

        if (msg.NotNullOrWhiteSpace())
            this.ErrorMessage = msg;
        else
            this.ErrorMessage = "{0}:只能由(字母、数字、中文、下滑线、点、@)组成，且只能(字母、数字、中文)开头";
    }

    /// <summary>
    /// 证请求结果
    /// </summary>
    /// <param name="value">校验内容</param>
    /// <param name="validationContext">报错指定对象</param>
    /// <returns>证请求结果的容器</returns>
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            Regex r = new Regex(@"^[A-Za-z0-9\u4e00-\u9fa5][\w|.|@|\u4e00-\u9fa5]{" + _minLength + "," + _maxLength + "}$");
            if (!r.IsMatch(value?.ToString()))
            {
                var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                return new ValidationResult(errorMessage);
            }
        }
        return ValidationResult.Success;
    }
}
